#include "mainwindow.h"
#include "./ui_mainwindow.h"

#include <QDebug>
#include <QDateTime>
#include <QFile>

#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>


MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    InitLayout();

    ConnectSignalSlot();
}

MainWindow::~MainWindow()
{
    delete ui;

    if (this->mThreadSerialPort)
    {   
        delete this->mThreadSerialPort;
        this->mThreadSerialPort = nullptr;
    }

    if (this->mPageSerialPortParemeters)
    {
        delete this->mPageSerialPortParemeters;
        this->mPageSerialPortParemeters = nullptr;
    }
}

void MainWindow::InitLayout()
{
    this->mThreadSerialPort = new ThreadSerialPort();

}

void MainWindow::ConnectSignalSlot()
{
    connect(ui->actionConnect, &QAction::triggered, this, [=](){
        qDebug() << "ui->actionConnect triggered";

        if (!isSerialPortConnected)
        {
            if (this->mPageSerialPortParemeters)
            {
                this->mPageSerialPortParemeters->show();
            }
            else
            {
                this->mPageSerialPortParemeters = new PageSerialPortParemeters();
                connect(this->mThreadSerialPort, &ThreadSerialPort::signalOpenSerialPort, this->mPageSerialPortParemeters, &PageSerialPortParemeters::slotOpenSerialPort);
                connect(this->mPageSerialPortParemeters, &PageSerialPortParemeters::signalConnectSerialPort, this->mThreadSerialPort, &ThreadSerialPort::slotOpenSerialPort);
                connect(this->mPageSerialPortParemeters, &PageSerialPortParemeters::destroyed, this, [=](){
                    this->mPageSerialPortParemeters = nullptr;
                });
                this->mPageSerialPortParemeters->show();
            }

        }
    });

    connect(ui->actionDisconnect, &QAction::triggered, this, [=](){
        if (isSerialPortConnected)
        {
            emit signalDisconnectSerialPort();
        }
    });

    connect(this, &MainWindow::signalDisconnectSerialPort, this->mThreadSerialPort, &ThreadSerialPort::slotCloseSerialPort);

    connect(this->mThreadSerialPort, &ThreadSerialPort::signalOpenSerialPort, this, [=](bool result, QString errStr){
        qDebug() << "connect " << result;
        isSerialPortConnected = result;
    });

    connect(this->mThreadSerialPort, &ThreadSerialPort::signalCloseSerialPort, this, [=](bool result){
        qDebug() << "disconnect " << result;
        isSerialPortConnected = !result;
    });

    connect(this->mThreadSerialPort, &ThreadSerialPort::signalReceivedData, this, [=](QString msg){
        qDebug() << "received data ";

        if (100 < this->mFrameCnt)
        {
            ui->textEdit->clear();
            this->mFrameCnt = 0;
        }

        ui->textEdit->append(msg);
        ui->textEdit->append("\n\n");

        SaveData(msg);
    });
}

void MainWindow::SaveData(QString msg)
{
    QDateTime currentDatatime = QDateTime::currentDateTime();
    QString fileName = QString("%1.csv").arg(currentDatatime.toString("yyyy-MM-dd"));
    QFile file(fileName);
    bool fileExists = file.exists();
    if (file.open(QIODevice::Append | QIODevice::Text))
    {
        QTextStream writeOut(&file);

        if (!fileExists)
        {
            writeOut << QString("时间") << ",";
            writeOut << QString("电流") << ",";
            for (int i = 1; i < 25; i++) {
                writeOut << QString("电压%1").arg(i) << ",";
            }
            for (int i = 1; i < 25; i++) {
                writeOut << QString("温度%1").arg(i) << ",";
            }
            writeOut << QString("继电器状态") << ",";
            writeOut << QString("均衡使能") << "\n";
        }


        QJsonDocument jsonDoc = QJsonDocument::fromJson(msg.toUtf8());
        QJsonObject jsonObject = jsonDoc.object();
        if (jsonObject.contains("DeviceID") &&
            jsonObject.contains("Current") &&
            jsonObject.contains("Voltages") &&
            jsonObject.contains("Temperatures") &&
            jsonObject.contains("RelayState") &&
            jsonObject.contains("EqualizationState"))
        {
            this->mFrameCnt++;

            float current = jsonObject.value("Current").toInt() / 1000.0;
            QJsonArray volArray = jsonObject.value("Voltages").toArray();
            QJsonArray temperatureArray = jsonObject.value("Temperatures").toArray();
            int relayState = jsonObject.value("RelayState").toInt();
            int equalizationState = jsonObject.value("EqualizationState").toInt();

            writeOut << currentDatatime.toString("yyyy/MM/dd HH:mm:ss") << ",";
            writeOut << current << ",";
            for (int i = 0; i < 24; i++) {
                writeOut << volArray[i].toInt() << ",";
            }
            for (int i = 0; i < 24; i++) {
                writeOut << temperatureArray[i].toInt() / 10.0 << ",";
            }
            writeOut << relayState << ",";
            writeOut << equalizationState << "\n";
        }

        file.close();
    }
}
